﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using AutoWelding.Models;
using AutoWelding.UControls;
using AutoWelding.Utils;
using AutoWelding.Views;
using AutoWelding.Views.Alarm;
using AutoWelding.Views.Documentation;
using AutoWelding.Views.Logs;
using AutoWelding.Views.Products;
using AutoWelding.Views.Recipes;
using AutoWelding.Views.Transmission;
using AutoWelding.Views.Users;
using AutoWelding.Views.Visual;

using log4net;

using MySql.Data.MySqlClient;

namespace AutoWelding
{

    public partial class MainForm : Form
    {
        //private static readonly ILog log = LogManager.GetLogger(typeof(MainForm));

        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 页面 初始化
        /// </summary>
        /// <param name="sender"></param
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            //初始化加载主页面
            LoadMainPage();
            /// 加载用户信息
            LoadUserInfo();
            //分页按钮事件
            RegisterPageBtnClick();

            initPageBtnTag();

            // 设置全局用户信息
            if (this.Tag is UserModel user)
            {
                AppContext.CurrentUser = user;
            }
        }

        private void initPageBtnTag()
        {
            upb_mainPage.Tag = typeof(Views.MainPageForm).FullName;
            upb_usersPage.Tag = typeof(Views.Users.UsersForm).FullName;
            upb_logsPage.Tag = typeof(Views.Logs.LogsForm).FullName;
            upb_alarmPage.Tag = typeof(Views.Alarm.AlarmForm).FullName;
            upb_recipesPage.Tag = typeof(Views.Recipes.RecipesForm).FullName;
            upb_productsPage.Tag = typeof(Views.Products.ProductsForm).FullName;
            upb_transmissionPage.Tag = typeof(Views.Transmission.TransmissionForm).FullName;
            upb_documentationPage.Tag = typeof(Views.Documentation.DocumentationForm).FullName;
            upb_visualPage.Tag = typeof(Views.Visual.VisualForm).FullName;
        }

        /// <summary>
        /// 窗体加载时，加载用户信息
        /// </summary>
        public void LoadUserInfo()
        {
            //获取用户名
            if (this.Tag is UserModel user)
            {
                //显示用户名
                label_username.Text = user.NickName;
                //Debug.WriteLine($"MainForm.Tag: {this.Tag}");
            }
            //获取用户权限
            //string identity = ConfigHelper.GetValue("identity");            //显示用户名
            //显示用户权限
            //lbl_identity.Text = identity;
        }

        #region 菜单按钮点击事件
        private void menuBtn_users_Click(object sender, EventArgs e)
        {
            SetMenuBtnBackColor(2);
            UsersForm frm = new UsersForm();
            if (this.Tag is UserModel user)
            {
                frm.Tag = user; // 直接传递UserModel对象
                Debug.WriteLine($"传递给子页面的用户信息: {user.NickName}"); // 传递了 但接收不到 换个方法吧
            }
            FormUtils.AddFormToPanel(panel_page, frm);
            BtnMenuIsSelected();
        }

        private void menuBtn_main_Click(object sender, EventArgs e)
        {
            LoadMainPage();
        }

        private void LoadMainPage()
        {
            SetMenuBtnBackColor(1);
            MainPageForm mainPage = new MainPageForm();
            FormUtils.AddFormToPanel(panel_page, mainPage);
            BtnMenuIsSelected();
        }
        private void menuBtn_logs_Click(object sender, EventArgs e)
        {
            SetMenuBtnBackColor(3);
            LogsForm logs = new LogsForm();
            FormUtils.AddFormToPanel(panel_page, logs);
            BtnMenuIsSelected();
        }
        private void menuBtn_alarm_Click(object sender, EventArgs e)
        {
            SetMenuBtnBackColor(4);
            AlarmForm alarm = new AlarmForm();
            FormUtils.AddFormToPanel(panel_page, alarm);
            BtnMenuIsSelected();
        }

        private void menuBtn_recipes_Click(object sender, EventArgs e)
        {
            SetMenuBtnBackColor(5);
            RecipesForm recipes = new RecipesForm();
            FormUtils.AddFormToPanel(panel_page, recipes);
            BtnMenuIsSelected();
        }

        private void menuBtn_porducts_Click(object sender, EventArgs e)
        {
            SetMenuBtnBackColor(6);
            ProductsForm products = new ProductsForm();
            FormUtils.AddFormToPanel(panel_page, products);
            BtnMenuIsSelected();
        }
        private void menuBtn_transmission_Click(object sender, EventArgs e)
        {
            SetMenuBtnBackColor(7);
            TransmissionForm transmissionForm = new TransmissionForm();
            FormUtils.AddFormToPanel(panel_page, transmissionForm);
            BtnMenuIsSelected();
        }
        private void menuBtn_documentation_Click(object sender, EventArgs e)
        {
            SetMenuBtnBackColor(8);
            DocumentationForm documentationForm = new DocumentationForm();
            FormUtils.AddFormToPanel(panel_page, documentationForm);
            BtnMenuIsSelected();
        }

        private void menuBtn_visual_Click(object sender, EventArgs e)
        {
            SetMenuBtnBackColor(9);
            VisualForm visualForm = new VisualForm();
            FormUtils.AddFormToPanel(panel_page, visualForm);
            BtnMenuIsSelected();
        }

        #endregion
        private void btn_closePage_Click(object sender, EventArgs e)
        {
            if (panel_page.Controls.Count > 0)
            {
                Form f = panel_page.Controls[0] as Form;
                f.Close();
                panel_page.Controls.Remove(f);
                //改变  分页按钮的字体颜色
                foreach (Control c in panel_pageTop.Controls)
                {
                    if (c is UPageButton)
                    {
                        UPageButton b = c as UPageButton;
                        if (b.Tag.ToString().Contains(f.Name) && b.Tag != null)
                        {
                            b.ForeColor = Color.White;
                            break;
                        }
                    }
                }
                //设置分页按钮可见和不可见
                if (this.panel_page.Controls.Count <= 0)
                {
                    btn_closePage.Visible = false;
                }
                BtnMenuIsSelected();
            }
            else
            {
                MessageBox.Show("没有可以关闭的页面！", "错误提示");
                return;
            }
        }
        /// <summary>
        /// 用户图标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        bool isShow = false;
        private void pictureBox2_Click(object sender, EventArgs e)
        {

            if (!isShow)
            {
                btn_loginout.Visible = true;
                btn_updatepwd.Visible = true;
                isShow = true;
            }
            else
            {
                btn_loginout.Visible = false;
                btn_updatepwd.Visible = false;
                isShow = false;
            }
        }

        #region 最小化、最大化、关闭页面按钮处理
        /// <summary>
        /// 最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uIconButton_min_Click(object sender, EventArgs e)
        {
            if (this.WindowState != FormWindowState.Minimized)
                this.WindowState = FormWindowState.Minimized;
        }

        /// <summary>
        /// 最大化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uIconButton_max_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
                uIconButton_max.Text = "1";
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
                uIconButton_max.Text = "2";
            }
        }
        /// <summary>
        /// 关闭页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uIconButton_close_Click(object sender, EventArgs e)
        {
            Application.Exit();
            LogHelper.Info(typeof(MainForm), label_username.Text + "用户退出系统");
        }

        /// <summary>
        /// 重写关闭方法
        /// </summary>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否退出系统?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Application.ExitThread();
            }
            else
                e.Cancel = true;
        }
        #endregion

        #region 移动窗体
        Point point = new Point();
        bool isMove = false;

        private void panel_top_MouseDown(object sender, MouseEventArgs e)
        {
            point = e.Location;//按住的点
            isMove = true;
        }

        private void panel_top_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && isMove)
            {
                Point pointNew = e.Location;//按住的点拖动到的位置
                Point fPointNew = new Point(pointNew.X - point.X, pointNew.Y - point.Y);//相对于原来起点的距离点的描述
                this.Location += new Size(fPointNew);

            }
        }
        #endregion

        #region 改变窗体大小
        const int WM_NCHITTEST = 0x0084;// 移动鼠标
        const int HTLEFT = 10;
        const int HTRIGHT = 11;
        const int HTTOP = 12;
        const int HTTOPLEFT = 13;
        const int HTTOPRIGHT = 14;
        const int HTBOTTOM = 15;
        const int HTBOTTOMLEFT = 0x10;
        const int HTBOTTOMRIGHT = 17;

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            switch (m.Msg)
            {
                case WM_NCHITTEST:
                    Point vPoint = new Point((int)m.LParam & 0xFFFF,
                   (int)m.LParam >> 16 & 0xFFFF);
                    vPoint = PointToClient(vPoint);
                    if (vPoint.X <= 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)HTTOPLEFT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)HTBOTTOMLEFT;
                        else m.Result = (IntPtr)HTLEFT;
                    else if (vPoint.X >= ClientSize.Width - 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)HTTOPRIGHT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)HTBOTTOMRIGHT;
                        else m.Result = (IntPtr)HTRIGHT;
                    else if (vPoint.Y <= 5)
                        m.Result = (IntPtr)HTTOP;
                    else if (vPoint.Y >= ClientSize.Height - 5)
                        m.Result = (IntPtr)HTBOTTOM;

                    break;
            }
        }

        #endregion

        #region 左侧菜单按钮  和 顶端页面按钮的处理

        /// <summary>
        /// 菜单按钮的背景色
        /// </summary>；l
        /// <param name="code"></param>
        private void SetMenuBtnBackColor(int code)
        {
            switch (code)
            {
                case 1:
                    //设置左侧主页面菜单按钮的背景颜色，其他按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_main, upb_mainPage);
                    break;
                case 2:
                    //设置左侧用户管理菜单按钮的背景颜色，其他按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_users, upb_usersPage);
                    break;
                case 3:
                    //设置左侧日志管理菜单按钮的背景颜色，其他按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_logs, upb_logsPage);
                    break;
                case 4:
                    //设置左侧报警管理菜单按钮的背景颜色，其他两钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_alarm, upb_alarmPage);
                    break;
                case 5:
                    //设置左侧配方管理菜单按钮的背景颜色，其他按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_recipes, upb_recipesPage);
                    break;
                case 6:
                    //设置左侧产品管理菜单按钮的背景颜色，其他按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_porducts, upb_productsPage);
                    break;
                case 7:
                    //设置左侧 transmission管理菜单按钮的背景颜色，其他按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_transmission, upb_transmissionPage);
                    break;
                case 8:
                    //设置左侧文档管理菜单按钮的背景颜色，其他按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_documentation, upb_documentationPage);
                    break;
                case 9:
                    //设置左侧文档管理菜单按钮的背景颜色，其他按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_visual, upb_visualPage);
                    break;
            }
        }

        /// <summary>
        /// 处理左边按钮背景色和分页按钮的文本颜色
        /// </summary>
        /// <param name="btn"></param>
        /// <param name="btnPage"></param>
        private void SetMenuBtnsColor(UMenuButton btn, UPageButton btnPage)
        {
            //模块按钮的背景色
            Color unSelColor = Color.Aqua;//未选中
            Color SelColor = Color.Blue;//选中
            //分页按钮文本颜色
            Color topSelColor = Color.FromArgb(45, 50, 116);//点击时或显示相关页面时
            Color topUnSelColor = Color.White;//默认或没有显示页面时

            //btn.BackColor = SelColor; // 改为通过 IsSelected 属性更改背景颜色
            btnPage.ForeColor = topSelColor;

            //处理未选中模块按钮、未显示 分页按钮
            UMenuButton[] menuBtns = { menuBtn_main, menuBtn_users, menuBtn_logs, menuBtn_alarm, menuBtn_recipes, menuBtn_porducts, menuBtn_transmission, menuBtn_documentation, menuBtn_visual };
            UPageButton[] pageBtns = { upb_mainPage, upb_usersPage, upb_logsPage, upb_alarmPage, upb_recipesPage, upb_productsPage, upb_transmissionPage, upb_documentationPage, upb_visualPage };

            //foreach (UMenuButton b in menuBtns) // 改为通过 IsSelected 属性更改背景颜色
            //{
            //    if (b.Name != btn.Name)
            //        b.BackColor = unSelColor;
            //}

            foreach (UPageButton b in pageBtns)
            {
                if (btnPage.Name != b.Name)
                    b.ForeColor = topUnSelColor;
            }
        }

        /// <summary>
        /// 注册按钮单击事件
        /// </summary>
        private void RegisterPageBtnClick()
        {
            foreach (Control c in panel_pageTop.Controls)
            {
                if (c is UPageButton)
                {
                    UPageButton btn = c as UPageButton;
                    btn.Click += upb_menu_Click;
                }
            }
        }
        /// <summary>
        /// 分页按钮点击事件    
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void upb_menu_Click(object sender, EventArgs e)
        {
            //分页按钮文本颜色
            Color topSelColor = Color.FromArgb(45, 50, 116);//点击时或显示相关页面时
            Color topUnSelColor = Color.White;//默认或没有显示页面时

            UPageButton clickBtn = sender as UPageButton;//当前点击按钮

            foreach (Control c in panel_pageTop.Controls)
            {
                if (c is UPageButton)
                {
                    UPageButton btn = c as UPageButton;
                    if (btn.Name != clickBtn.Name)
                    {
                        btn.ForeColor = topUnSelColor;
                    }
                }
            }

            //切换页面的实现处理
            if (clickBtn.Tag != null)
            {
                string frmFullName = clickBtn.Tag.ToString();
                int lastIndex = frmFullName.LastIndexOf('.');
                string frmName = frmFullName.Substring(lastIndex + 1);

                Form f = FormUtils.GetOpenForm(frmName);
                if (f == null)
                {
                    //实例化页面
                    f = (Form)Activator.CreateInstance(Type.GetType(frmFullName));
                }
                panel_page.AddFormToPanel(f);

                if (frmName == "")
                {

                }
                //处理关闭按钮的显示
                ShowClosePageBtn();
                BtnMenuIsSelected();
            }
        }

        private void ShowClosePageBtn()
        {
            if (panel_page.Controls.Count > 0)
            {
                btn_closePage.Visible = true;
            }
            else
            {
                btn_closePage.Visible = false;
            }
        }

        #endregion

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_loginout_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出登录吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                //能否退出登陆的一些判断
                //CheckIsLoginOut();
                //如果可以执行退出登录逻辑
                //LoginForm login = new LoginForm();
                //login.Show();
                //this.Hide();

            }

        }

        private void btn_updatepwd_Click(object sender, EventArgs e)
        {
            UpdatePwdForm updatePwd = new UpdatePwdForm();
            //获取用户名
            if (this.Tag is UserModel user)
            {
                updatePwd.Tag = user.UserId;
                updatePwd.Show();
            }
        }

        /// <summary>
        /// 根据当前打开的页面来设置左侧导航栏按钮的选中状态（变色）
        /// </summary>
        private void BtnMenuIsSelected()
        {
            menuBtn_main.IsSelected = false;
            menuBtn_recipes.IsSelected = false;
            menuBtn_transmission.IsSelected = false;
            menuBtn_users.IsSelected = false;
            menuBtn_logs.IsSelected = false;
            menuBtn_porducts.IsSelected = false;
            menuBtn_alarm.IsSelected = false;
            menuBtn_documentation.IsSelected = false;
            menuBtn_visual.IsSelected = false;


            if (panel_page.Controls.Count > 0)
            {
                //foreach (Form f in panel_page.Controls) // panelPage里面只有一个控件 不需要遍历
                //if (panel_page.Controls[0] is Form f) // 感觉页不需要判断
                Form f = panel_page.Controls[0] as Form; // 直接转换 因为确定是 Form

                // 添加调试信息
                Debug.WriteLine($"当前表单: {f}");
                Debug.WriteLine($"当前表单: {f.Name}");
                Debug.WriteLine($"表单类型: {f.GetType().Name}");

                //switch (f.Name)
                switch (f.GetType().Name) // 使用类型名进行判断
                {
                    case "MainPageForm":
                        menuBtn_main.IsSelected = true;
                        break;
                    case "RecipesForm":
                        menuBtn_recipes.IsSelected = true;
                        break;
                    case "TransmissionForm":
                        menuBtn_transmission.IsSelected = true;
                        break;
                    case "UsersForm":
                        menuBtn_users.IsSelected = true;
                        break;
                    case "LogsForm":
                        menuBtn_logs.IsSelected = true;
                        break;
                    case "ProductsForm":
                        menuBtn_porducts.IsSelected = true;
                        break;
                    case "AlarmForm":
                        menuBtn_alarm.IsSelected = true;
                        break;
                    case "DocumentationForm":
                        menuBtn_documentation.IsSelected = true;
                        break;
                    case "VisualForm":
                        menuBtn_visual.IsSelected = true;
                        break;
                }
            }
        }

    }
}
